<template>
  <div class="recipients-container">
    <div class="dashboard-card" style="padding: 20px;">
      <div class="card-header">
        <h3>收件人管理</h3>
        <div class="header-actions">
          <el-input
            v-model="searchText"
            placeholder="搜索姓名或邮箱"
            style="width: 250px; margin-right: 10px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon> 添加收件人
          </el-button>
        </div>
      </div>

      <!-- 收件人表格 -->
      <el-table :data="filteredRecipients" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱地址" width="220" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editRecipient(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteRecipient(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑收件人' : '添加收件人'"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="姓名" required>
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱地址" required>
          <el-input v-model="form.email" placeholder="请输入邮箱地址" type="email" />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="部门">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
        
        <el-form-item label="职位">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="form.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { recipientAPI } from '@/api'

const recipients = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref({
  name: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  is_active: true,
  description: ''
})

// 过滤收件人
const filteredRecipients = computed(() => {
  if (!searchText.value) {
    return recipients.value
  }
  const search = searchText.value.toLowerCase()
  return recipients.value.filter(recipient => {
    return recipient.name.toLowerCase().includes(search) ||
           recipient.email.toLowerCase().includes(search) ||
           (recipient.department && recipient.department.toLowerCase().includes(search)) ||
           (recipient.position && recipient.position.toLowerCase().includes(search))
  })
})

// 获取收件人列表
const fetchRecipients = async () => {
  try {
    const data = await recipientAPI.list()
    recipients.value = data.results || data
  } catch (error) {
    ElMessage.error('获取收件人列表失败')
  }
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  form.value = {
    name: '',
    email: '',
    phone: '',
    department: '',
    position: '',
    is_active: true,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑收件人
const editRecipient = (recipient) => {
  isEdit.value = true
  form.value = { ...recipient }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  // 验证必填字段
  if (!form.value.name || !form.value.email) {
    ElMessage.warning('请填写姓名和邮箱地址')
    return
  }
  
  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(form.value.email)) {
    ElMessage.error('邮箱格式不正确')
    return
  }
  
  try {
    if (isEdit.value) {
      await recipientAPI.update(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await recipientAPI.create(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchRecipients()
  } catch (error) {
    const errorMsg = error.response?.data?.email?.[0] || '操作失败'
    ElMessage.error(errorMsg)
  }
}

// 删除收件人
const deleteRecipient = (recipient) => {
  ElMessageBox.confirm(`确定要删除收件人 "${recipient.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await recipientAPI.delete(recipient.id)
      ElMessage.success('删除成功')
      fetchRecipients()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

onMounted(() => {
  fetchRecipients()
})
</script>

<style scoped>
.recipients-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #3a84ff;
  font-size: 20px;
}
</style>
